package util;

import java.io.File;
import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Properties;
import java.util.Scanner;

import dao.DBException;
/**
 * Provides access to text files.
 * @author Jolle
 * @version 1.0.0
 */
public class FileAccess {
	
	private String curFilePath = "";
	private RandomAccessFile curRAFile = null;
	/**
	 * check whether file exists
	 * @param fileName
	 * @return true if it exists
	 */
	public boolean fileExists(String fullPath) {
		File file = new File(fullPath);
		return (file.exists());
	}
	/**
	 * read the whole content of the given text file
	 * @param fullPath to the file
	 * @return String content
	 * @throws Exception
	 */
	public String readFile(String fullPath) throws DBException {
	    String content = "";
		File file = new File(fullPath);
		if (!fileExists(fullPath)) {
			return content;
		}
		try {
			Scanner scanner = new Scanner(file);
			content = scanner.useDelimiter("\\Z").next();
			scanner.close();
	    } catch (Exception e) {
	    	throw new DBException("Problems while reading file", e);
	    }
	    return content;
	}
	/**
	 * read a single line from given INI file
	 * @param fullPath to the file
	 * @return String line
	 * @throws Exception
	 */
	public String readLine(String fullPath) throws DBException {
	    String line = null;
		try {
		    if (this.curRAFile == null) {
				if (!fileExists(fullPath)) {
					//throw new FileNotFoundException();
					return null;
				}
				File file = new File(fullPath);
				this.curFilePath = fullPath;
				this.curRAFile = new RandomAccessFile(file, "r");
			}
			if (this.curFilePath.equalsIgnoreCase(fullPath)) {
				line = this.curRAFile.readLine();
				if (line == null) {
					this.curRAFile.close();
					this.curFilePath = "";
					this.curRAFile = null;
				}
			}
			else {
				throw new DBException("Different file open");
			}
		} catch (Exception e) {
			throw new DBException("Problems while reading line", e);
		}
		return line;
	}
	/**
	 * read all properties from given INI or XML file
	 * @param fullPath to the file
	 * @return Properties collection
	 * @throws Exception
	 */
	public Properties readPropertiesFromIni(String fullPath) throws DBException {
		Properties props = new Properties();
		try {
			if(fullPath.toLowerCase().endsWith(".xml")) {
				props.loadFromXML(new FileInputStream(fullPath));
			}
			else {
				props.load(new FileInputStream(fullPath));
			}
		} catch (Exception e) {
			throw new DBException("Problems while reading properties", e);
		}
	    return props;
	}
}
